package com.innjia.base.utils.pdf;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import javax.servlet.http.HttpServletRequest;

import com.innjia.base.common.Config;
import com.innjia.base.utils.HttpContextUtils;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.Image;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.ColumnText;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfGState;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;
/**
 * iText生成水印
 * 每页都添加
 *
 * @author mbc
 */


public class WaterMarks{

    private Font font;  //文本字体
    private String text; // 水印文本
    private float rotation; //文本旋转角度
    private String filePath; //pdf文件路径
    public WaterMarks() {

    }

    /**
     *
     * @param filePath pdf文件路径
     * @param text  水印文本
     */
    public WaterMarks(String filePath,String text) {
        this.filePath = filePath;
        this.text = text;
        this.rotation = 0;
        try {
            this.font = new Font(CustomFont.getDefaultFont(), 80);
            addWaterMarks();
        } catch (DocumentException | IOException e) {
            e.printStackTrace();
        }

    }
    /**
     *
     * @param filePath  pdf文件路径
     * @param text      水印文本
     * @param fontSize  字体大小
     */
    public WaterMarks(String filePath,String text, float fontSize) {
        this.filePath = filePath;
        this.text = text;
        this.rotation = 0;
        try {
            this.font = new Font(CustomFont.getDefaultFont(), fontSize);
            addWaterMarks();
        } catch (DocumentException | IOException e) {
            e.printStackTrace();
        }

    }

    /**
     *
     * @param filePath  pdf文件路径
     * @param text      水印文本
     * @param fontSize  字体大小
     * @param rotation  旋转角度
     */
    public WaterMarks(String filePath,String text, float fontSize,float rotation) {
        this.filePath = filePath;
        this.text = text;
        this.rotation = rotation;
        try {
            this.font = new Font(CustomFont.getDefaultFont(), fontSize);
            addWaterMarks();
        } catch (DocumentException | IOException e) {
            e.printStackTrace();
        }
    }

    public static byte[] imageWaterMarks(final byte[] pdfBytes) {
    	String path = Config.getFileStore() + File.separator + "contract" + File.separator + "temp" + File.separator + "temp.pdf";
    	InputStream inputStream = null;
    	byte[] b = null;
    	File file = new File(path);
    	try {
    		if(!(file.getParentFile().exists())) {
    			file.getParentFile().mkdirs();
    			file.createNewFile();
    		};
    		PdfReader reader = new PdfReader(pdfBytes);
    		PdfStamper stamp = new PdfStamper(reader, new FileOutputStream(path));
    		PdfContentByte under = stamp.getUnderContent(1);
    		HttpServletRequest request = HttpContextUtils.getHttpServletRequest();
    		Image img = Image.getInstance(request.getServletContext().getRealPath("/") + "/statics/image/blockChain.png");
    		img.setAbsolutePosition(370, 610);
    		under.addImage(img);
    		stamp.close();
    		inputStream = new FileInputStream(file);
    		b = new byte[inputStream.available()];
    		inputStream.read(b, 0, b.length);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if(inputStream != null) {
				try {
					inputStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if(file != null && file.exists()) {
				file.delete();
			}
		}
    	return b;
    }

    private void addWaterMarks() throws IOException, DocumentException{
        String dest = "temp.pdf";
        PdfReader reader = new PdfReader(this.filePath);
        int n = reader.getNumberOfPages();
        PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(dest));
        //水印文本
        Phrase p = new Phrase(text, font);
        PdfGState gs1 = new PdfGState();
        //水印透明度
        gs1.setFillOpacity(0.1f);
        // properties
        PdfContentByte over;
        Rectangle pagesize;
        float x, y;
        // 每个页面都添加水印
        for (int i = 1; i <= n; i++) {
            pagesize = reader.getPageSizeWithRotation(i);
            x = (pagesize.getLeft() + pagesize.getRight()) / 2;
            y = (pagesize.getTop() + pagesize.getBottom()) / 2;
            over = stamper.getOverContent(i);
            over.saveState();
            over.setGState(gs1);
            ColumnText.showTextAligned(over, Element.ALIGN_CENTER, p, x, y, this.rotation);
        }
        stamper.close();
        reader.close();

        File sfile = new File(this.filePath);
        File nfile = new File(dest);
        //删除原文件
        if(sfile.isFile() && sfile.exists()){
            sfile.delete();
        }
        //重命名新文件为原文件
        if(nfile.isFile() && nfile.exists()){
            nfile.renameTo(new File(this.filePath));
        }

    }
}
